<template>
  <van-card
      :thumb="actorInfo.avatar"
      :title="actorInfo.name"
      :desc="actorInfo.create_time"
  ></van-card>
</template>

<script lang="ts">
import { getTokenFunc, setTokenFunc, delTokenFunc, getJwtPayloadFunc, setStoreAccessTokenNameFunc, setStoreRefreshTokenNameFunc, setTokenPrefixFunc, setTokenSuffixFunc } from '../script/common'
// 请求相关
import { safeRequestFunc } from '../script/service'
// 引入Vant组件
import { Toast, Card } from 'vant'

export default {
  name: 'ActorInfo',
  inject: {
    APP_NAME: {
      from: 'APP_NAME',
      default: '',
    },
    componentConfig: {
      from: 'componentConfig',
      default() {
        return {
          // 授权接口
          API_ACTOR_AUTH: '',
          // Token接口
          API_ACTOR_TOKEN: '',
          // 信息接口
          API_ACTOR_INFO: '',
          // 授权绑定
          API_ACTOR_AUTH_BIND: '',
          // 用户类型
          ACTOR_TYPE: '',
          // 数据总线
          DATA_HUB_ACTOR_INFO: '',
          // TOKEN名
          STORE_ACCESS_TOKEN_NAME: '',
          STORE_REFRESH_TOKEN_NAME: '',
        }
      },
    },
    dataHubSet: 'dataHubSet',
    dataHubGet: 'dataHubGet',
  },
  components: {
    Toast,
    [Card.name]: Card,
  },
  props: {
    // 活动详情
    mainData: {
      type: Object,
      default () {
        return {
          id: 0,
        }
      },
    },
  },
  data () {
    return {
      // 参与信息
      actorInfo: {},
      token: {
        accessToken: '',
        refreshToken: '',
      },
    }
  },
  // 数据监听
  watch: {
    // 监听主数据变化
    'mainData.id': {
      immediate: true,
      async handler (newValue) {
        console.log('[Actor组件]#监听mainData.id变化：', newValue)
        if (newValue) {
          // Token后缀
          setTokenSuffixFunc('_' + newValue)
        }
      }
    },
    'token.accessToken': {
      immediate: true,
      async handler (newValue) {
        console.log('[watch@ACTOR_TOKEN]#监听AccessToken变化：', newValue)
        if (newValue) {
          // 获取角色信息
          await this.infoFunc()
        }
      }
    },
  },
  // 计算属性
  computed: {

  },
  // 组件挂载
  mounted() {
    // Token前缀
    // @ts-ignore
    this.APP_NAME && setTokenPrefixFunc( this.APP_NAME + '_')
    // AccessToken名
    // @ts-ignore
    this.componentConfig?.STORE_ACCESS_TOKEN_NAME && setStoreAccessTokenNameFunc(this.componentConfig.STORE_ACCESS_TOKEN_NAME)
    // RefreshToken名
    // @ts-ignore
    this.componentConfig?.STORE_REFRESH_TOKEN_NAME && setStoreRefreshTokenNameFunc(this.componentConfig.STORE_REFRESH_TOKEN_NAME)
  },
  methods: {
    // 参与信息
    async infoFunc () {
      console.log('[Actor组件@infoFunc]#请求')
      let [apiError, apiResult] = await safeRequestFunc({
        loginAuth: true, // 需要登陆认证
        url: this.componentConfig?.API_ACTOR_INFO,
        method: 'post',
        data: {
          main_id: this.mainData?.id || 0
        },
      })
      console.log('[Actor组件@infoFunc]#接口返回', apiError, apiResult)
      if (apiError || apiResult.code != 1) {
        Toast.fail(apiError || apiResult.msg)
        return null
      }
      this.actorInfo = apiResult.data
      // 设置到总线
      if (this.componentConfig?.DATA_HUB_ACTOR_INFO) {
        this.dataHubSet(this.componentConfig.DATA_HUB_ACTOR_INFO, this.actorInfo)
      }
      return this.actorInfo
    },
    // 授权登陆
    async authLoginFunc (commonToken: string = ''): Promise<any[]> {
      try {
        // 刷新登陆
        let [refreshLoginError, refreshLoginResult] = await this.refreshLoginFunc()
        console.log('[Actor组件@actorAuthLoginFunc]#刷新登陆', refreshLoginError, refreshLoginResult)
        if (refreshLoginError && refreshLoginError !== 'NotToken') {
          return Promise.resolve([refreshLoginError, null])
        }
        if (refreshLoginResult) {
          return Promise.resolve([null, refreshLoginResult])
        }
        // region 授权登陆 +++++
        if (!commonToken) {
          return Promise.resolve(['NotCommonToken', null])
        }
        // 授权接口
        if (!this.componentConfig?.API_ACTOR_AUTH) {
          return Promise.resolve(['授权登陆接口配置错误', null])
        }
        let [apiError, apiResult] = await safeRequestFunc({
          url: this.componentConfig?.API_ACTOR_AUTH,
          method: 'post',
          data: {
            main_id: this.mainData?.id || 0,
          },
          headers: {
            Authorization: 'bearer ' + commonToken
          }
        })
        console.log('[Actor组件@actorAuthLoginFunc]#授权登陆信息', apiError, apiResult)
        if (apiError || apiResult.code !== 1) {
          return Promise.resolve([apiError || apiResult.msg, null])
        }
        // 设置TOKEN
        this.token = setTokenFunc(apiResult.data.access_token, apiResult.data.refresh_token)
        return Promise.resolve([null, {
          accessToken: apiResult.data.access_token,
          refreshToken: apiResult.data.refresh_token
        }])
      } catch (exception) {
        console.log('[Actor组件@actorAuthLoginFunc]#异常', exception)
        return Promise.resolve(['[Actor组件@actorAuthLoginFunc]#异常:' + exception.message, null])
      }
    },
    // 刷新登陆
    async refreshLoginFunc () {
      console.log('[Actor组件@refreshLoginFunc]#开始执行')
      try {
        // 取得本地TOKEN
        let token = getTokenFunc()
        console.log('[Actor组件@refreshLoginFunc]#获取TOKEN', token)
        if (token) {
          // 解析TOKEN
          let jwtPayload = getJwtPayloadFunc(token.accessToken)
          console.log('[Actor组件@refreshLoginFunc]#解析TOKEN负载', jwtPayload)
          if (!jwtPayload) {
            throw new Error('TOKEN解析失败')
          }
          if (jwtPayload.master_id != this.mainData.id || jwtPayload.user_type != this.componentConfig?.ACTOR_TYPE) {
            throw new Error('TOKEN数据错误')
          }
          // @ts-ignore
          if ($GP.Util.dayJS().unix() + 30 >= jwtPayload.exp) {
            console.log('[Actor组件@refreshLoginFunc]#TOKEN过期')
            if (!this.componentConfig?.API_ACTOR_TOKEN) {
              return Promise.resolve(['刷新接口配置错误', null])
            }
            // 刷新TOKEN
            let [apiError, apiResult] = await safeRequestFunc({
              url: this.componentConfig?.API_ACTOR_TOKEN,
              method: 'post',
              data: {
                main_id: this.mainData?.id || 0,
                refresh_token: token.refreshToken
              },
              headers: {
                Authorization: 'bearer ' + token.accessToken
              }
            })
            console.log('[Actor组件@refreshLoginFunc]#TOKEN刷新', apiError, apiResult)
            if (apiError || apiResult.code !== 1) {
              // 刷新失败删除本地存储
              delTokenFunc()
              return Promise.resolve([apiError || apiResult.msg, null])
            }
            // 更新TOKEN
            token.accessToken = apiResult.data.access_token
            // 设置TOKEN
            token = setTokenFunc(token.accessToken)
          }
          this.token = token
          return Promise.resolve([null, token])
        }
        return Promise.resolve(['NotToken', null])
      } catch (exception) {
        console.log('[Actor组件@refreshLoginFunc]#异常', exception)
        return Promise.resolve(['[Actor组件@refreshLoginFunc]#异常:' + exception.message, null])
      }
    },
    // 角色认证绑定
    async authBindFunc (bindToken: string) {
      if (!bindToken) {
        Toast.fail('缺少BindToken参数')
        return null
      }
      let [apiError, apiResult] = await safeRequestFunc({
        loginAuth: true, // 需要登陆认证
        url: this.componentConfig?.API_ACTOR_AUTH_BIND,
        method: 'post',
        data: {
          main_id: this.mainData?.id || 0,
          bind_token: bindToken
        },
      })
      console.log('[Actor组件@authBindFunc]#请求结果', apiError, apiResult)
      if (apiError || apiResult.code !== 1) {
        Toast.fail(apiError || apiResult.msg)
        return null
      }
      // 设置TOKEN
      this.token = setTokenFunc(apiResult.data.access_token)
      return true
    },
  },
}
</script>

<style lang="scss" scoped>
.van-card__thumb {
  width: 35px;
  height: 35px;
}
.van-card__content {
  min-height: auto;
}
</style>
